package com.yupi.yangapigateway;

import com.yangmao.yangapi_client_sdk.utils.SignUtils;
import com.yangmao.yangapicommon.model.entity.InterfaceInfo;
import com.yangmao.yangapicommon.model.entity.User;
import com.yangmao.yangapicommon.service.InnerInterfaceInfoService;
import com.yangmao.yangapicommon.service.InnerUserInterfaceInfoService;
import com.yangmao.yangapicommon.service.InnerUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 全局过滤
 */
@Slf4j
@Component
public class CustomGlobalFilter implements GlobalFilter, Ordered {

    private static final List<String> IP_WHITE_LIST = Arrays.asList("127.0.0.1","localhost");

    @DubboReference
    private InnerUserService innerUserService;

    @DubboReference
    private InnerInterfaceInfoService innerInterfaceInfoService;

    @DubboReference
    private InnerUserInterfaceInfoService innerUserInterfaceInfoService;

    private static final String INTERFACE_HOST = "http://localhost:8123";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //1.请求日志
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String method = request.getMethod().toString();
        String path = INTERFACE_HOST + request.getPath().value();
        log.info("请求Id："+ request.getId());
        log.info("请求路径："+ path );
        log.info("请求参数："+ request.getQueryParams());
        String sourceAddress = request.getLocalAddress().getHostString();
        log.info("请求地址："+ sourceAddress);
        log.info("请求方法："+ method);

        //2.访问控制 - （黑白名单）
        if(!IP_WHITE_LIST.contains(sourceAddress)){
            return handleNoAuth(response);
        }
        //3. 请求鉴权（判断accessKey secretKey是否合法）
        HttpHeaders headers = request.getHeaders();
        String accessKey = headers.getFirst("accessKey");
        String timestamp = headers.getFirst("timestamp");
        String nonce = headers.getFirst("nonce");
        String body = headers.getFirst("body");
        String sign = headers.getFirst("sign");

        //实际情况中是数据库中查询是否给用户分配权限
        User invokeUser = null;
        try {
            invokeUser = innerUserService.getInvokeUser(accessKey);
        } catch (Exception e){
            log.error("getInvokeUser error");
        }
        if(invokeUser == null){
            return handleNoAuth(response);
        }

//        if (!accessKey.equals("yangmao")) {
//            return handleNoAuth(response);
//        }

        if (Long.parseLong(nonce) > 10000) {
            return handleNoAuth(response);
        }

        Long currentTime = System.currentTimeMillis() / 1000;
        final Long FIVE_MINUTE = 60 * 5L;
        if ((currentTime - Long.parseLong(timestamp)) >= FIVE_MINUTE) {
            return handleNoAuth(response);
        }

        // 从数据库中查询出secretKey
        String secretKey = invokeUser.getSecretKey();
        String serverSign = SignUtils.genSign(body, secretKey);

        if (sign == null || !sign.equals(serverSign)) {
            return handleNoAuth(response);
        }
        //4. 判断调用的模拟接口是否存在
        InterfaceInfo interfaceInfo = null;
        try {
            interfaceInfo = innerInterfaceInfoService.getInterfaceInfo(path,method);
        } catch (Exception e){
            log.error("getInterfaceInfo error");
        }
        if(interfaceInfo == null){
            return handleNoAuth(response);
        }

        // todo 网关判断是否还有调用次数

        //5. 请求转发，调用模拟接口 + 响应日志
//        Mono<Void> filter = chain.filter(exchange);
        return handleResponse(exchange,chain, interfaceInfo.getId(), invokeUser.getId());

    }


    /**
     * 处理响应
     * @param exchange
     * @param chain
     * @return
     */
    public Mono<Void> handleResponse(ServerWebExchange exchange, GatewayFilterChain chain , long interfaceId, long userId) {
        try {
            ServerHttpResponse originalResponse = exchange.getResponse();

            DataBufferFactory dataBufferFactory = originalResponse.bufferFactory();

            HttpStatus statusCode = (HttpStatus) originalResponse.getStatusCode();

            if (statusCode == HttpStatus.OK) {
                ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {

                    @Override
                    public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                        //log.info("body instanceof Flux: {}", (body instanceof Flux));
                        if (body instanceof Flux) {
                            Flux<? extends DataBuffer> fluxBody = Flux.from(body);
                            //
                            return super.writeWith(
                                    fluxBody.map(dataBuffer -> {
                                        // 7. 调用成功，调用次数+1 invokeCount
                                        try {
                                            innerUserInterfaceInfoService.invokeCount(interfaceId,userId);
                                        } catch (Exception e) {
                                            log.info("invokeCount error",e);
                                        }
                                        byte[] content = new byte[dataBuffer.readableByteCount()];
                                        dataBuffer.read(content);
                                        DataBufferUtils.release(dataBuffer);//释放掉内存
                                        // 构建日志
                                        StringBuilder sb2 = new StringBuilder(200);
                                        List<Object> rspArgs = new ArrayList<>();
                                        rspArgs.add(originalResponse.getStatusCode());
                                        //rspArgs.add(requestUrl);
                                        String data = new String(content, StandardCharsets.UTF_8);//data
                                        sb2.append(data);
                                        // 打印日志
                                        log.info("响应结果：" + data);//log.info("<-- {} {}\n", originalResponse.getStatusCode(), data);
                                        return dataBufferFactory.wrap(content);
                                    }));
                        } else {
                            // 8.调用失败，返回一个规范的错误码
                            log.error("<--- {} 响应code异常", getStatusCode());
                        }
                        return super.writeWith(body);
                    }
                };
                return chain.filter(exchange.mutate().response(decoratedResponse).build());
            }
            return chain.filter(exchange);//降级处理返回数据
        } catch (Exception e) {
            log.error("网关处理响应异常" + e);
            return chain.filter(exchange);
        }
    }

    @Override
    public int getOrder() {
        return -1;
    }

    private Mono<Void> handleNoAuth(ServerHttpResponse response){
        response.setStatusCode(HttpStatus.FORBIDDEN);
        return response.setComplete();
    }

    private Mono<Void> handleInvokeError(ServerHttpResponse response){
        response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
        return response.setComplete();
    }
}